package io.renren.modules.skate.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.read.builder.ExcelReaderBuilder;
import com.alibaba.excel.read.builder.ExcelReaderSheetBuilder;
import io.renren.common.annotation.LogOperation;
import io.renren.common.constant.Constant;
import io.renren.common.page.PageData;
import io.renren.common.utils.DateUtils;
import io.renren.common.utils.ExcelUtils;
import io.renren.common.utils.Result;
import io.renren.common.validator.AssertUtils;
import io.renren.common.validator.ValidatorUtils;
import io.renren.common.validator.group.AddGroup;
import io.renren.common.validator.group.DefaultGroup;
import io.renren.common.validator.group.UpdateGroup;
import io.renren.modules.security.user.SecurityUser;
import io.renren.modules.security.user.UserDetail;
import io.renren.modules.skate.dto.FAthleteDTO;
import io.renren.modules.skate.entity.FClubEntity;
import io.renren.modules.skate.excel.FAthleteExcel;
import io.renren.modules.skate.excel.FClubExcel;
import io.renren.modules.skate.listener.FAthleteListener;
import io.renren.modules.skate.service.FAthleteService;
import io.renren.modules.skate.service.FClubService;
import io.renren.modules.sys.entity.SysRoleUserEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysRoleUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
* 运动员表
*
* @author Mark sunlightcs@gmail.com
* @since 3.0 2023-11-28
*/
@RestController
@RequestMapping("skate/fathlete")
@Api(tags="运动员表")
public class FAthleteController {
    @Autowired
    private FAthleteService fAthleteService;

    @Autowired
    private FClubService fClubService;
    @Autowired
    private SysRoleUserService sysRoleUserService;

    @GetMapping("page")
    @ApiOperation("分页")
    @ApiImplicitParams({
        @ApiImplicitParam(name = Constant.PAGE, value = "当前页码，从1开始", paramType = "query", required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.LIMIT, value = "每页显示记录数", paramType = "query",required = true, dataType="int") ,
        @ApiImplicitParam(name = Constant.ORDER_FIELD, value = "排序字段", paramType = "query", dataType="String") ,
        @ApiImplicitParam(name = Constant.ORDER, value = "排序方式，可选值(asc、desc)", paramType = "query", dataType="String")
    })
    @RequiresPermissions("skate:fathlete:page")
    public Result<PageData<FAthleteDTO>> page(@ApiIgnore @RequestParam Map<String, Object> params){
        // 获取当前用户的角色
        UserDetail userDetail = SecurityUser.getUser();
        List<Long> roleIdList = sysRoleUserService.getRoleIdList(userDetail.getId());
        boolean isClub = false;
        for(Long roleId : roleIdList){
            if(Constant.CLUBROLEID.equals(roleId)){
                isClub = true;
                break;
            }
        }
        // 如果是俱乐部角色，只能查看自己俱乐部的运动员
        if(isClub){
            params.put("clubId", userDetail.getClubId());
        }
        PageData<FAthleteDTO> page = fAthleteService.page(params);
        page.getList().forEach(dto ->{
            if(dto.getClubId()!=null){
                FClubEntity fClubEntity = fClubService.selectById(dto.getClubId().longValue());
                if(fClubEntity!=null) {
                    dto.setClubName(fClubEntity.getClubName());
                }
            }
        });
        return new Result<PageData<FAthleteDTO>>().ok(page);
    }

    @GetMapping("{id}")
    @ApiOperation("信息")
    @RequiresPermissions("skate:fathlete:info")
    public Result<FAthleteDTO> get(@PathVariable("id") Long id){
        FAthleteDTO data = fAthleteService.get(id);

        return new Result<FAthleteDTO>().ok(data);
    }

    @PostMapping
    @ApiOperation("保存")
    @LogOperation("保存")
    @RequiresPermissions("skate:fathlete:save")
    public Result save(@RequestBody FAthleteDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, AddGroup.class, DefaultGroup.class);
        // 设置运动员编号，编号取日期+4位流水号
        String code = DateUtils.format(new Date(), "yyyyMMdd");
        String maxNo = fAthleteService.getMaxNo();
        // maxNo不为空，说明数据库中有数据，取最大的编号
        if(maxNo != null) {
            String no = maxNo.substring(8);
            int noInt = Integer.parseInt(no);
            noInt++;
            code += String.format("%04d", noInt);
        }
        dto.setNumber(code);
        dto.setCreator(SecurityUser.getUserId().toString());
        dto.setUpdater(SecurityUser.getUserId().toString());
        dto.setCreateDate(new Date());
        dto.setUpdateDate(new Date());
        fAthleteService.save(dto);

        return new Result();
    }

    @PutMapping
    @ApiOperation("修改")
    @LogOperation("修改")
    @RequiresPermissions("skate:fathlete:update")
    public Result update(@RequestBody FAthleteDTO dto){
        //效验数据
        ValidatorUtils.validateEntity(dto, UpdateGroup.class, DefaultGroup.class);
        dto.setUpdater(SecurityUser.getUserId().toString());
        dto.setUpdateDate(new Date());
        fAthleteService.update(dto);

        return new Result();
    }

    @DeleteMapping
    @ApiOperation("删除")
    @LogOperation("删除")
    @RequiresPermissions("skate:fathlete:delete")
    public Result delete(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");

        fAthleteService.delete(ids);

        return new Result();
    }

    @GetMapping("export")
    @ApiOperation("导出")
    @LogOperation("导出")
    @RequiresPermissions("skate:fathlete:export")
    public void export(@ApiIgnore @RequestParam Map<String, Object> params, HttpServletResponse response) throws Exception {
        List<FAthleteDTO> list = fAthleteService.list(params);

        ExcelUtils.exportExcelToTarget(response, null, "运动员表", list, FAthleteExcel.class);
    }
    /**
     * 导入俱乐部
     * @param file
     * @return
     * @throws Exception
     */
    @PostMapping("import")
    @ApiOperation("导入")
    @ApiImplicitParam(name = "file", value = "文件", paramType = "query", dataType="file")
    public Result importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        Result result = new Result();
        ExcelReaderBuilder readCertificate = EasyExcel.read(file.getInputStream(), FAthleteExcel.class, new FAthleteListener(result, fAthleteService));

        ExcelReaderSheetBuilder sheet = readCertificate.sheet();

        sheet.doRead();

        return result;
    }


   @PostMapping("batchRenZheng")
    @RequiresPermissions("skate:fathlete:renzheng")
    public Result batchRenZheng(@RequestBody Long[] ids){
        //效验数据
        AssertUtils.isArrayEmpty(ids, "id");
        fAthleteService.batchRenZheng(ids);
        return new Result();
    }

}